﻿#if USE_PIPES
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using log4net;
using OdsServer.Common.DataTransfer;
using OdsServer.Common.Packet;
using OdsServer.Common;

namespace OdsServer.DataTransfer.Pipes
{
    internal class PipeTransfer : IDataPublisherAgent
    {
        private static readonly ILog log    = LogManager.GetLogger(typeof(PipeTransfer));
        private Thread listenerThread       = null;
        private volatile bool threadQuit    = false;

        // WinAPI named pipe objects
        private List<NamedPipeServerStream> outPipes    = null;
        private NamedPipeServerStream inPipe            = null;

        private static readonly string inPipeName   = OdsServerConfiguration.GetInstance().PipeTransfer.InPipeName;
        private static readonly string outPipeName  = OdsServerConfiguration.GetInstance().PipeTransfer.OutPipeName;

        public event DataPublisherFaultDelegate OnFault;

        public void StartAgent()
        {
            this.outPipes = new List<NamedPipeServerStream>();

            try
            {
                this.inPipe = new NamedPipeServerStream(
                        inPipeName,
                        PipeDirection.In);
            }
            catch (IOException ioe)
            {
                // log pipe name conflict
                log.ErrorFormat(
                        "StartService / Pipe conflict occured: {0} while init on pipe: {1}",
                        ioe.Message,
                        inPipeName);
                return;
            }
            catch (PlatformNotSupportedException pnse)
            {
                log.ErrorFormat(
                        "StartService / Platform configuration fault: {0} while init on pipe: {1}",
                        pnse.Message,
                        inPipeName);
                return;
            }

            this.listenerThread                 = new Thread(this.ListenerTask);
            this.listenerThread.IsBackground    = true;

            this.listenerThread.Start();
        }

        private void ListenerTask()
        {
            while (!threadQuit)
            {
                if (this.inPipe != null
                        && !this.inPipe.IsConnected)
                {
                    this.inPipe.WaitForConnection();
                }

                Thread.Sleep(10);
            }
        }

        public void StopAgent()
        {
            throw new NotImplementedException();
        }

        public void Publish(object sender, IBasePacket data)
        {
            throw new NotImplementedException();
        }

        public void ReportFault(DataTransferException e)
        {
            if (this.OnFault != null)
                this.OnFault(this, e);
        }
    }
}
#endif